#!/bin/bash

# 清理端口并启动服务的脚本

echo "🔧 清理端口并启动 ReactIM 服务..."

# 定义端口
USER_SERVICE_PORT=8081
MESSAGE_SERVICE_PORT=8082
FRONTEND_PORT=3000

# 函数：杀死指定端口的进程
kill_port() {
    local port=$1
    local service_name=$2
    
    echo "🔍 检查端口 $port ($service_name)..."
    
    # 查找占用端口的进程
    local pid=$(lsof -ti:$port)
    
    if [ ! -z "$pid" ]; then
        echo "⚠️  端口 $port 被进程 $pid 占用，正在终止..."
        kill -9 $pid
        sleep 1
        echo "✅ 端口 $port 已清理"
    else
        echo "✅ 端口 $port 未被占用"
    fi
}

# 清理所有端口
echo "🧹 清理所有服务端口..."
kill_port $USER_SERVICE_PORT "用户服务"
kill_port $MESSAGE_SERVICE_PORT "消息服务"
kill_port $FRONTEND_PORT "前端服务"

echo ""
echo "🚀 启动服务..."

# 启动用户服务
echo "📦 启动用户服务 (端口: $USER_SERVICE_PORT)..."
cd reactim-user-service
nohup mvn spring-boot:run > ../logs/user-service.log 2>&1 &
USER_SERVICE_PID=$!
cd ..

# 等待用户服务启动
echo "⏳ 等待用户服务启动..."
sleep 10

# 检查用户服务是否启动成功
if curl -s http://localhost:$USER_SERVICE_PORT/actuator/health > /dev/null; then
    echo "✅ 用户服务启动成功"
else
    echo "❌ 用户服务启动失败"
    exit 1
fi

# 启动消息服务
echo "📦 启动消息服务 (端口: $MESSAGE_SERVICE_PORT)..."
cd reactim-message-service
nohup mvn spring-boot:run > ../logs/message-service.log 2>&1 &
MESSAGE_SERVICE_PID=$!
cd ..

# 等待消息服务启动
echo "⏳ 等待消息服务启动..."
sleep 10

# 检查消息服务是否启动成功
if curl -s http://localhost:$MESSAGE_SERVICE_PORT/actuator/health > /dev/null; then
    echo "✅ 消息服务启动成功"
else
    echo "❌ 消息服务启动失败"
    exit 1
fi

# 启动前端服务
echo "📦 启动前端服务 (端口: $FRONTEND_PORT)..."
cd h5-messaging-client
nohup npm run dev > ../logs/frontend.log 2>&1 &
FRONTEND_PID=$!
cd ..

# 等待前端服务启动
echo "⏳ 等待前端服务启动..."
sleep 5

# 检查前端服务是否启动成功
if curl -s http://localhost:$FRONTEND_PORT > /dev/null; then
    echo "✅ 前端服务启动成功"
else
    echo "❌ 前端服务启动失败"
fi

echo ""
echo "🎉 所有服务启动完成！"
echo "📊 服务状态："
echo "   - 用户服务: http://localhost:$USER_SERVICE_PORT (PID: $USER_SERVICE_PID)"
echo "   - 消息服务: http://localhost:$MESSAGE_SERVICE_PORT (PID: $MESSAGE_SERVICE_PID)"
echo "   - 前端服务: http://localhost:$FRONTEND_PORT (PID: $FRONTEND_PID)"
echo ""
echo "📝 日志文件："
echo "   - 用户服务: logs/user-service.log"
echo "   - 消息服务: logs/message-service.log"
echo "   - 前端服务: logs/frontend.log"
echo ""
echo "🛑 要停止所有服务，请运行: ./stop-services.sh"